package com.illtamer.infinite.sillage.controller;

import com.illtamer.infinite.sillage.annotation.Convert;
import com.illtamer.infinite.sillage.entity.ViewHandler;
import com.illtamer.infinite.sillage.pojo.Comment;
import com.illtamer.infinite.sillage.service.BlogService;
import com.illtamer.infinite.sillage.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

@Controller
@RequestMapping("/detail")
public class DetailController {

    @Resource
    private ApplicationContext context;

    @Resource(name = "blogService")
    private BlogService blogService;

    @Resource(name = "commentService")
    private CommentService commentService;

    @RequestMapping
    public String detail(@RequestParam("id") Integer id, Model model) {
        context.getBean(ViewHandler.class).record(id);
        model.addAttribute("blog", blogService.selectByIdAndConvert(id));
        return "detail";
    }

    @RequestMapping("/comment")
    public String comment(@RequestParam("blogId") Integer blogId, Model model) {
        model.addAttribute("comments", commentService.listTopCommentByBlogId(blogId));
        return "detail::commentList";
    }

    @PostMapping("/comment/submit")
    public String submitComment(@Convert Comment comment) {
        commentService.saveComment(comment);
        return "forward:/detail/comment";
    }

}
